//
//  YDUserData.m
//  YDExtension
//
//  Created by rowena on 2019/9/17.
//  Copyright © 2019 wuyezhiguhun. All rights reserved.
//

#import "YDUserData.h"
#import <objc/runtime.h>

@interface YDUserData()<NSCoding>

@end

@implementation YDUserData

/**
 * 归档时调用
 */
- (void)encodeWithCoder:(NSCoder *)aCoder {
    unsigned int count;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i++) {
        Ivar iva = ivar[i];
        const char *name = ivar_getName(iva);
        NSString *strName = [NSString stringWithUTF8String:name];
        //利用KVC取值
        id value = [self valueForKey:strName];
        //进行归档
        [aCoder encodeObject:value forKey:strName];
    }
    free(ivar);
}
/**
 * 接档时调用
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivar = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar iva = ivar[i];
            const char *name = ivar_getName(iva);
            NSString *strName = [NSString stringWithUTF8String:name];
            //进行解档取值
            id value = [aDecoder decodeObjectForKey:strName];
            //利用KVC对属性赋值
            [self setValue:value forKey:strName];
        }
        free(ivar);
    }
    return self;
}

/** 打印类日志 */
- (NSString *)description {
    return [NSString stringWithFormat:@"name=%@ icon=%@", _name, _icon];
}



@end
